/* eslint-disable strict */

$(function() {

  // 切换皮肤
  const colors = [];
  const $themes = $('#color-options > li > a');
  $themes.each((index, item) => {
    colors.push(item.id);
  });
  const currentColor = localStorage.getItem('theme');
  if (currentColor) {
    let targetActive = 1;
    colors.forEach((item, index) => {
      if (currentColor === item) {
        targetActive = index;
      }
    });
    $('#color-options').find('li').eq(targetActive)
      .addClass('active');
  } else {
    $('#color-options li:first-child').addClass('active');
  }

  $themes.on('click', function() {
    $(document.documentElement).attr('data-theme', this.id);
    localStorage.setItem('theme', this.id);
  });

  $('#color-options').on('click', 'li', function() {
    $(this).addClass('active').siblings()
      .removeClass('active');
  });
  // 检测webp
  function checkWebp(img) {
    const webImg = new Image();
    webImg.src = '';
    webImg.onload = function() {
      const result = webImg.width > 0 && webImg.height > 0;
      if (!result) {
        img.src = '/public/home/images/win10狗头.jpg';
      }
    };
    webImg.onerror = function() {
      img.src = '/public/home/images/win10狗头.jpg';
    };
  }

  checkWebp(document.querySelector('.profile-image'));

  // 点击切换颜色按钮
  $('#config-trigger').click(function(e) {
    e.preventDefault();
    if ($(this).hasClass('config-panel-open')) {
      $('#config-panel').animate(
        {
          right: '-=190',
        },
        500
      );
      $(this).removeClass('config-panel-open').addClass('config-panel-hide');
    } else {
      $('#config-panel').animate(
        {
          right: '+=190',
        },
        500
      );
      $(this).removeClass('config-panel-hide').addClass('config-panel-open');
    }
  });
  $('#config-close').on('click', function(e) {
    e.preventDefault();
    $('#config-trigger').click();
  });

  // url header li高亮
  const currenPage = location.href;
  $('.navbar-nav > .nav-item:nth-child(1)').addClass('active');

  function removeFirstActive() {
    $('.navbar-nav > .nav-item:nth-child(1)').removeClass('active');
  }

  // 热门博客
  if (currenPage.includes('hot')) {
    removeFirstActive();
    $('.navbar-nav > .nav-item:nth-child(2)').addClass('active');
  }
  // 分类
  if (currenPage.includes('list')) {
    removeFirstActive();
    $('.navbar-nav > .nav-item:nth-child(3)').addClass('active');
  }
  // 详情页
  if (currenPage.includes('article')) {
    removeFirstActive();
  }

  // 高亮关键词
  const searchContent = location.search;
  if (searchContent && searchContent.includes('?search')) {
    const search = decodeURIComponent(searchContent.split('?search=')[1]);
    if ($('.title a').length !== 0) {
      $('.title a').each((index, ele) => {
        // ele is a HTMLElement
        const title = $(ele).html();
        const reg = new RegExp(search, 'gi');
        const newSearchContent = title.match(reg);
        const newTitle = newSearchContent.reduce((total, cur) => {
          return total.replace(cur, `<mark class="highlightTitle">${cur}</mark>`);
        }, title);
        $(ele).html(newTitle);
      });
    } else {
      $('footer').addClass('fixed');
      $('.blog-list > .container').text('空空如也，世界变得清净了~');
    }
  }

  // 动态logo
  const $logo = $('.logo'),
    logoArr = [ ...$logo.text() ];
  logoArr.reduce((pre, cur, index) => {
    pre === index && $logo.html('');
    const span = document.createElement('span');
    const $span = $(span);
    $span.html(cur);
    $logo.append($span);
    $span.on('mouseover', function() {
      $(this).addClass('color');
    });
    $span.on('animationend', function() {
      $(this).removeClass('color');
    });
  }, 0);

  // 回到顶部
  const windowTop = $(window).height();
  const $back = $('.back_top');
  $(document).on('scroll', function() {
    if ($(document).scrollTop() >= windowTop / 2) {
      $back.fadeIn();
    } else {
      $back.fadeOut();
    }
  });
  $back.on('click', function() {
    $('body ,html').stop().animate({
      scrollTop: 0,
    });
  });

  // 懒加载内容
  const options = {
    threshold: 1,
    rootMargin: '0px',
  };

  function lazyLoad(index, target) {
    const io = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          const src = $(img).attr('data-src');
          $(img).attr('src', src);
          observer.disconnect();
        }
      });
    }, options);
    io.observe(target);
  }

  if (typeof IntersectionObserver !== 'function') {
    const listImgsSrc = $('.img-list');
    listImgsSrc.each(function() {
      const imgSrc = this.getAttribute('data-src');
      $(this).attr('src', imgSrc);
    });
  } else {
    $('.item img').each(lazyLoad);
  }

  // 分类页select框
  $('#inlineFormCustomSelect').on('change', function() {
    const cid = $('#inlineFormCustomSelect option:checked').val();
    const listName = $('#inlineFormCustomSelect option:checked').text();
    $.get('/ajax_list', { cid }, datas => {
      if (datas.success) {
        const documentFragment = document.createDocumentFragment();
        datas.message.forEach(data => {
          const div = $('<div class="item mb-5"></div>')[0];
          div.innerHTML = `
          <div class="media">
            <img
              src="https://dummyimage.com/110x110.png?text=shixtao.cn"
              class="img-list mr-3 img-fluid post-thumb d-none d-md-flex"
              data-src=${data.img}
            />
          <div class="media-body">
            <h2 class="title mb-1">
              <a href="/article/${data.id}">${data.title}</a>
            </h2>
            <div class="meta mb-1">
              <i class="iconfont icon-bokeyuan"></i>
              <span title="博客类型"
                >${data.type}&nbsp;
                <span class="text-info">
                  ${listName}
                </span>
              </span>
              <i class="iconfont icon-shizhong"></i>
              <span title="发表时间">${data.time}</span>
              <i class="iconfont icon-renyuan"></i>
              <span title="博客作者">${data.author}</span>
              <i class="iconfont icon-pinglun"></i>
              <span title="评论"
                ><a href="/article/${data.id}#form"
                  >${data.comment} 评论</a
                ></span
              >
              <i class="iconfont icon-liulan"></i>
              <span title="浏览量">${data.click}</span>
            </div>
            <div class="intro">${data.description}</div>
            <a class="more-link" href="/article/${data.id}"
              >更多内容 &rarr;</a
            >
          </div>
        </div>
          `;
          documentFragment.appendChild(div);
        });
        $('.blog-list > .container').html(documentFragment);
        $('.item img').each(lazyLoad);
      } else {
        location.href = '/list';
      }
    });
  });

  /**
   * 为文本域添加emoji
   * @param {HTMLTextAreaElement} textArea 需要添加表情的文本域
   * @param {string} str 当前emoji
   */
  function changeEmoji(textArea, str) {
    textArea.setRangeText(str);
    textArea.selectionStart += str.length;
    textArea.focus();
  }

  const $commentSmileIcon = $('.comment_smile_icon');
  const $replySmileIcon = $('.reply_smile_icon');
  const $replySmileIcon2 = $('.reply_smile_icon2');
  $commentSmileIcon.on('click', function(e) {
    $('.emoji_box').toggle();
    e.stopPropagation();
  });
  $replySmileIcon.on('click', function(e) {
    $('.emoji_box').toggle();
    e.stopPropagation();
  });
  $replySmileIcon2.on('click', function(e) {
    $('.emoji_box').toggle();
    e.stopPropagation();
  });
  $('.comment_emoji_item').on('click', function(e) {
    const emoji = e.target.innerText;
    const textArea = $commentSmileIcon.siblings('.form-control')[0];
    changeEmoji(textArea, emoji);
  });
  $('.reply_emoji_item').on('click', function(e) {
    const emoji = e.target.innerText;
    const textArea = $replySmileIcon.siblings('.form-control')[0];
    changeEmoji(textArea, emoji);
  });
  $('.reply_emoji_item2').on('click', function(e) {
    const emoji = e.target.innerText;
    const textArea = $replySmileIcon2.siblings('.form-control')[0];
    changeEmoji(textArea, emoji);
  });
  $('body').on('click', function() {
    const $emojiBox = $('.emoji_box');
    const flag = $emojiBox.css('display');
    if (flag === 'block') {
      $emojiBox.hide();
    }
  });
});
